#include "globals.h"

void 
congestion_control ( 
        arq_params* win, 
        int rcwin, 
        int * cwin, 
        int * ssthrsh, 
        int cwin_congestion,
        int serv_win
        )
{
	int min;

	if( win->win_r == 0 && win->win_l == 0 )
	{
		win->win_size = * cwin;
		*ssthrsh = rcwin;		
	}	
	else if(cwin_congestion == FALSE) //No congestion
	{
		printf("No Congestion in the Network\n");
		if ( *cwin*2 <= *ssthrsh ) // Slow start
		{
			printf("Slow Start Phase ... \n");
			* cwin *= 2;			
		}
		else // Congestion Avoidance
		{
			printf("Congestion Avoidance Phase ... \n");
			*cwin += 1;
		}

        if( *cwin > (min = rcwin < serv_win? rcwin: serv_win) )
        {
            if(min == serv_win)
            {
                printf("Congestion window size (%d) > Server sending window size (%d) ... New value of Congestion window = %d \n", *cwin, serv_win, min);
            }
            else
            {
                printf("Congestion window size (%d) > Receiver window size (%d) ... New value of Congestion window = %d\n", *cwin, rcwin, min);
            }   
            *cwin = min;
        }   
        
        win->win_size = *cwin;
	}	
	else //congestion
	{
		printf("Congestion in the Network ... Initiating slow start\n");	
		*ssthrsh = *ssthrsh/2;
		*cwin = 1;
		win->win_size = *cwin;		 
	}
	printf("\nSending %d datagram/s SST %d\n", *cwin, *ssthrsh);		
}
